﻿using System.Reflection;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using OrderApi.Data;
using OrderApi.Helpers;
using OrderApi.Repositories;
using OrderApi.Services;

var builder = WebApplication.CreateBuilder(args);

// 添加编码支持（解决中文导出问题）
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

// 添加 Swagger 服务
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "订单管理系统 API",
        Version = "v1",
        Description = "订单管理系统的 RESTful API，包括订单的增删改查、分页查询和Excel导出功能",
        Contact = new OpenApiContact
        {
            Name = "开发团队",
            Email = "dev@example.com"
        }
    });

    // 安全包含 XML 文档
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath);
    }
    else
    {
        // 仅在开发环境记录此警告
        if (builder.Environment.IsDevelopment())
        {
            Console.WriteLine($"⚠️ XML 文档文件未找到: {xmlPath}");
            Console.WriteLine("解决方案:");
            Console.WriteLine("1. 确保项目启用了 XML 文档生成");
            Console.WriteLine("   <GenerateDocumentationFile>true</GenerateDocumentationFile>");
            Console.WriteLine("2. 重新生成解决方案");
            Console.WriteLine("3. 检查文件是否存在于 bin 目录中");
        }
    }
    // 为枚举值添加描述
    c.UseInlineDefinitionsForEnums();

    // 使用控制器和动作的摘要作为操作描述
    c.OperationFilter<SwaggerOperationFilter>();

    // 显示模型属性为 camelCase（可选）
    c.DescribeAllParametersInCamelCase();

    // 设置API文档更新时间
    c.DocumentFilter<LastModifiedDocumentFilter>();
});

// Add services to the container
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped<IOrderService, OrderService>();


builder.Services.AddControllers();

var app = builder.Build();
// 配置 HTTP 请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "订单管理系统 API V1");
        c.RoutePrefix = "swagger";
        c.ConfigObject.DisplayRequestDuration = true;
    });
}
// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

// 应用数据库迁移
ApplyDatabaseMigrations(app);

app.Run();

void ApplyDatabaseMigrations(WebApplication app)
{
    using var scope = app.Services.CreateScope();
    var services = scope.ServiceProvider;

    try
    {
        var dbContext = services.GetRequiredService<AppDbContext>();
        dbContext.Database.Migrate();
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "应用数据库迁移时发生错误");
    }
}